import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_topic_list_state.dart';
import 'package:casdon/modules/lifeCircle/domain/usecase/life_self_topic_list_usecase.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LifeSelfTopicListNotifier
    extends AutoDisposeAsyncNotifier<LifeTopicListState> {
  int pageSize = 10;
  int pageNum = 1;

  @override
  Future<LifeTopicListState> build() async {
    return _fetchData();
  }

  Future<void> refresh() async {
    try {
      pageNum = 1;
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<LifeTopicListState> _fetchData() async {
    final ret = await ref
        .read(lifeSelfTopicListUsecaseProvider)
        .execute(pageNum: pageNum, pageSize: pageSize);
    final topics = (ret.rows ?? []).map((topic) {
      return LifeTopicModule.fromApi(
        topic,
      ).copyWith(isFollow: true); // 刻意设置为true，为了在我的主页中帖子列表不会展示关注按钮
    }).toList();
    return LifeTopicListState(
      data: topics,
      totalSize: ret.total,
      page: pageNum,
      pageSize: pageSize,
      isLoadingMore: false,
      hasMore: ret.total > (ret.rows ?? []).length,
    );
  }

  Future<void> loadMore() async {
    final current = state.valueOrNull;
    if (current == null || current.isLoadingMore || !current.hasMore) return;
    if ((current.data?.length ?? 0) >= current.totalSize) {
      return;
    }
    state = AsyncValue.data(current.copyWith(isLoadingMore: true));

    final nextPage = current.page + 1;
    final ret = await ref
        .read(lifeSelfTopicListUsecaseProvider)
        .execute(pageNum: nextPage, pageSize: pageSize);

    state = AsyncValue.data(
      LifeTopicListState(
        data: [
          ...current.data ?? [],
          ...LifeTopicModule.listFromApi(ret.rows ?? []),
        ],
        page: nextPage,
        totalSize: ret.total,
        pageSize: current.pageSize,
        isLoadingMore: false,
        hasMore:
            ret.total > (current.data ?? []).length + (ret.rows ?? []).length,
      ),
    );
  }

  void removeTopicById(String topicId) {
    ref.read(lifeDelTopicUsecaseProvider).execute(id: topicId);

    final current = state.valueOrNull;
    final currentData = current?.data;
    if (current == null || currentData == null) return;

    final newData = currentData.where((topic) => topic.id != topicId).toList();
    final newState = current.copyWith(
      data: newData,
      totalSize: current.totalSize > 0 ? current.totalSize - 1 : 0,
      hasMore: newData.length < current.totalSize,
    );
    state = AsyncValue.data(newState);
  }
}

final lifeSelfTopicListNotifierProvider =
    AutoDisposeAsyncNotifierProvider<
      LifeSelfTopicListNotifier,
      LifeTopicListState
    >(() => LifeSelfTopicListNotifier());
